import hashlib
import http
import json
import time
import urllib
import re
import pymysql
import pymysql.connections
from flask import Flask, jsonify, request
from flask_cors import CORS
import collections
import http.client, urllib, json

collections.Iterable = collections.abc.Iterable

from numpy import random
import server.models.sms_classify as clf

# 连接数据库
db = pymysql.connect(host='bj-cynosdbmysql-grp-r6nm8iqk.sql.tencentcdb.com', user='root', password='20201314OKok.',
                     database='db_computerdesign', port=26231)
db1 = pymysql.connect(host='bj-cynosdbmysql-grp-r6nm8iqk.sql.tencentcdb.com', user='root', password='20201314OKok.',
                      database='db_computerdesign', port=26231)
key = 'ea6ead968263dadf8b9439621e497994'
app = Flask(__name__)
# 解决跨域问题
CORS(app)


@app.route('/', methods=['GET'])
def index():
    return jsonify('sms classify api, request </predict> get result.')


# 登录
@app.route('/login.do', methods=['POST'])
def login():
    account = request.form['account']
    password = request.form['password']
    print(account)
    cursor = db.cursor()
    sql = "SELECT * FROM tb_user WHERE account=%s AND password=%s"
    cursor.execute(sql, (account, password))
    res = cursor.fetchone()
    cursor.close()
    if res:
        # 登录成功
        return jsonify(result=1)
    else:
        # 登录失败
        return jsonify(result=0)


# 注册
@app.route('/register.do', methods=['POST'])
def register():
    try:
        # python中request.args.get获取get请求的值
        # python中request.form.get获取post请求的值
        # python中request.form['']获取post请求的json值
        account = request.form.get('account')
        password = request.form.get('password')
        print(account)
        cursor = db.cursor()
        sql = "INSERT INTO tb_user (account, password) VALUES (%s, %s)"
        row = cursor.execute(sql, (account, password))
        db.commit()

    except pymysql.connect.Error as e:
        return jsonify(result=0)
    finally:
        cursor.close()
    if row == 1:
        return jsonify(result=1)
    else:
        return jsonify(result=0)


# pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query') 连接超时
# 查询邮件总数
@app.route('/get_predict_num.do', methods=['GET'])
def get_predict_num():
    cursor = db.cursor()
    sql = "SELECT COUNT(*) FROM tb_history"
    cursor.execute(sql)
    res = cursor.fetchone()[0]
    print(res)
    cursor.close()
    return jsonify(result=res)


# 查询邮件总数
@app.route('/get_grabage_num.do', methods=['GET'])
def get_grabage_num():

    cursor = db1.cursor()
    sql = "SELECT COUNT(*) FROM tb_history where label = 'ham'"
    cursor.execute(sql)
    res = cursor.fetchone()[0]
    cursor.close()
    return jsonify(result=res)



# 查询历史记录
@app.route('/queryHistory.do', methods=['post'])
def queryHistory():
    cursor = db.cursor()
    sql = "SELECT * FROM tb_history"
    cursor.execute(sql)
    results = cursor.fetchall()
    cursor.close()

    # 将结果转换为字典列表
    history_list = []
    for result in results:
        history = {
            'email': result[0],
            'label': result[1]
        }
        history_list.append(history)
    print(history_list)
    return jsonify(history_list)


def addHistory(email, result):
    try:
        cursor = db.cursor()
        sql = "INSERT INTO tb_history (email, label) VALUES (%s, %s)"
        row = cursor.execute(sql, (email, result))
        db.commit()
        if row == 1:
            print('添加历史记录成功')
            return True
        else:
            print('添加历史记录失败')
            return False
    except pymysql.connect.Error as e:
        return False
    finally:
        cursor.close()


# 模型训练
@app.route('/train.do', methods=['GET', 'POST'])
def train():
    accuracy = clf.train()
    time.sleep(8)
    return jsonify(result=1, accuracy=accuracy)


# 垃圾邮件预测
@app.route('/predict.do', methods=['GET'])
def sms_classify():
    email = request.args.get('email')
    print('当前email', email)
    Pattern = re.compile(u'[\u4e00-\u9fa5]+')
    match = Pattern.search(email)
    if match:
        tr_email = translate_(email, flag=1)
        end_email = tr_email
    else:
        end_email = email
    print('处理email', end_email)
    # 这里引入status来返回前端输出为空或者重复输入的情况
    result = clf.predict(end_email)
    print(result)
    if addHistory(email, result):
        return jsonify(email=email, label=result, status=1)
    else:
        return jsonify(email=email, label=result, status=0)


# @app.route('/get_')
# def :
##下面是api调用的函数
# 文本纠错
@app.route('/similarity.do', methods=['GET'])
def similarity():
    text1 = request.args.get('text1')
    text2 = request.args.get('text2')
    print(text1,text2)
    conn = http.client.HTTPSConnection('apis.tianapi.com')  # 接口域名
    params = urllib.parse.urlencode({'key': key, 'text1': text1, 'text2': text2})
    headers = {'Content-type': 'application/x-www-form-urlencoded'}
    conn.request('POST', '/simnet/index', params, headers)
    tianapi = conn.getresponse()
    result = tianapi.read()
    data = result.decode('utf-8')
    dict_data = json.loads(data)
    print(dict_data)
    score = dict_data['result']['score']
    print(score)
    return jsonify(result=score)

# 文本摘要
@app.route('/summary.do', methods=['GET'])
def summary():
    text = request.args.get('text3')
    conn = http.client.HTTPSConnection('apis.tianapi.com')  # 接口域名
    params = urllib.parse.urlencode({'key': key,
                                     'text': text,
                                     'length': '30'})
    headers = {'Content-type': 'application/x-www-form-urlencoded'}
    conn.request('POST', '/autoabstract/index', params, headers)
    tianapi = conn.getresponse()
    result = tianapi.read()
    data = result.decode('utf-8')
    dict_data = json.loads(data)
    print(dict_data)
    result = dict_data['result']['summary']
    print(result)
    return jsonify(result=result)
#邮件内容分类
@app.route('/content.do', methods=['GET'])
def content():
    text = request.args.get('text4')
    print(text)
    conn = http.client.HTTPSConnection('apis.tianapi.com')  # 接口域名
    params = urllib.parse.urlencode({'key': key, 'text': text})
    headers = {'Content-type': 'application/x-www-form-urlencoded'}
    conn.request('POST', '/textclass/index', params, headers)
    tianapi = conn.getresponse()
    result = tianapi.read()
    data = result.decode('utf-8')
    dict_data = json.loads(data)
    print(dict_data)
    result = dict_data['result']['first']
    return jsonify(result=result)

#邮件翻译
@app.route('/translate.do', methods=['GET'])
def translate():
    text = request.args.get('text5')
    conn = http.client.HTTPSConnection('apis.tianapi.com')  # 接口域名
    params = urllib.parse.urlencode({'key': key, 'text': text})
    headers = {'Content-type': 'application/x-www-form-urlencoded'}
    conn.request('POST', '/fanyi/index', params, headers)
    tianapi = conn.getresponse()
    result = tianapi.read()
    data = result.decode('utf-8')
    dict_data = json.loads(data)
    result = dict_data['result']['dst']
    return jsonify(result=result)
def translate_(translate_text, flag=1):
    appid = '20230412001638083'  # 填写你的appid
    secretKey = 'zEE7nJoLDuajGrYxsxlO'  # 填写你的密钥
    httpClient = None
    myurl = '/api/trans/vip/translate'  # 通用翻译API HTTP地址
    fromLang = 'auto'  # 原文语种

    if flag:
        toLang = 'en'  # 译文语种
    else:
        toLang = 'zh'  # 译文语种

    salt = random.randint(3276, 65536)
    sign = appid + translate_text + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(translate_text) + '&from=' + fromLang + \
            '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign

    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)
        return result['trans_result'][0]['dst']

    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=5000)
